<template>
    <d2-container type="full">
        <mk-search-form :model="query" @search="getData()">
            <el-form-item class="inline-item" prop="dayDate">
                <el-date-picker v-model.trim="query.selMonth" type="month" size="mini" value-format="yyyy-MM" clearable
                    placeholder="选择月份">
                </el-date-picker>
            </el-form-item>
        </mk-search-form>

        <div class="table-operate">
            <el-button size="mini" icon="el-icon-upload" @click="exportEcx">导出</el-button>
        </div>

        <el-table :data="dayArr" :height="heightL" :row-style="rowStyle" style="margin-top: 20px" id="tabledatalist">
            <el-table-column prop="day" :label="query.selMonth.slice(-2) + '月'" min-width="100" align="center" fixed="left">
                <template slot-scope="scope">
                    {{ scope.row.type ? scope.row.type : scope.row.day + '日' }}
                </template>
            </el-table-column>
            <template v-for="(item, index) in tableData">
                <el-table-column :label="shopList[index]" align="center">

                    <el-table-column :prop="`${index}-dailyIncomeScrapingCard`" label="刮刮卡转入" align="center" min-width="75">
                        <template slot-scope="scope">
                            {{ (item[scope.row.day - 1] && item[scope.row.day - 1].dailyIncomeScrapingCard) ?
                                item[scope.row.day -
                                    1].dailyIncomeScrapingCard : '--' }}
                        </template>
                    </el-table-column>

                    <el-table-column :prop="`${index}-dailyOutScrapingCard`" label="刮刮卡转出（当日）" align="center"
                        min-width="75">
                        <template slot-scope="scope">
                            {{ (item[scope.row.day - 1] && item[scope.row.day - 1].dailyOutScrapingCard) ?
                                item[scope.row.day -
                                    1].dailyOutScrapingCard : '--' }}
                        </template>
                    </el-table-column>

                    <el-table-column :prop="`${index}-nextDailyOutScrapingCard`" label="刮刮卡转出（次日）" align="center"
                        min-width="75">
                        <template slot-scope="scope">
                            {{ (item[scope.row.day - 1] && item[scope.row.day - 1].nextDailyOutScrapingCard) ?
                                item[scope.row.day -
                                    1].nextDailyOutScrapingCard : '--' }}
                        </template>
                    </el-table-column>

                </el-table-column>
                <el-table-column min-width="40" class-name="occupy-black" align="center"></el-table-column>
            </template>
            <el-table-column prop="total" label="刮刮卡当日注入转出合计" align="center" min-width="75">
                <template slot-scope="scope">
                    {{ totalList[scope.row.day - 1] || '--' }}
                </template>
            </el-table-column>
        </el-table>
    </d2-container>
</template>

<script>
import { scrapingCardRecord, scrapingCardRecordDay, scrapingCardRecordTotal } from '@/api/modules/sys.report.api'
import Tools from '@/libs/utils.tool'
import { exportExecl } from '@/libs/util.export'
import FileSaver from "file-saver";
import * as XLSX from "xlsx";

export default {
    name: 'index',
    data() {
        return {
            query: {
                selMonth: Tools.fmtLong2DateTime(new Date(), 'yyyy-MM')
            },
            dayArr: [],
            tableData: [],
            totalList: [],
            shopList: [],
            mp: null,
            ep: null,
            heightL: null
        }
    },
    created() {
        this.getData()
        this.getWinHeight()
    },
    methods: {
        // 获取所有数据
        async getData() {
            // 清空表单值
            this.tableData = []
            this.dayArr = []
            this.totalList = []

            const date = new Date(this.query.selMonth)
            date.setDate(1)
            const firstDay = date.toLocaleDateString()
            const dateEnd = new Date(this.query.selMonth)
            dateEnd.setMonth(dateEnd.getMonth() + 1)
            dateEnd.setDate(0)
            const lastDay = dateEnd.toLocaleDateString()
            // 所有数据
            const res = await scrapingCardRecord({
                startTime: `"${firstDay}"`,
                endTime: `"${lastDay}"`
            })
            const shopList = []
            const retArr = []
            // 将不同的店区分开
            res.map(item => {
                if (shopList.includes(item.shop)) {
                    retArr[shopList.indexOf(item.shop)].push(item)
                } else {
                    shopList.push(item.shop)
                    retArr.push([item])
                }
            })

            // 合计数据
            const resTotal = await scrapingCardRecordDay({
                startTime: `"${firstDay}"`,
                endTime: `"${lastDay}"`
            })

            // 不同店铺合计值
            this.mp = await scrapingCardRecordTotal({
                startTime: `"${firstDay}"`,
                endTime: `"${lastDay}"`
            })

            // 店内各项销售占比
            // this.ep = await getEachStoreProportion({
            //     startTime: `"${firstDay}"`,
            //     endTime: `"${lastDay}"`
            // })

            this.shopList = shopList
            this.handleData(retArr, resTotal)
        },
        // 数据处理
        handleData(res, resTotal) {
            // 获取本月总共多少天
            // const days = new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0).getDate()

            const days = new Date(new Date(this.query.selMonth).getFullYear(), new Date(this.query.selMonth).getMonth() + 1, 0).getDate()
            // 创建本月所有的天
            let totalSum = 0
            for (let i = 1; i <= days; i++) {
                this.dayArr.push({ day: i })
                let temp = ''
                // 处理销售总额
                for (let j = 0; j < resTotal.length; j++) {
                    if (Number(Tools.fmtLong2DateTime(resTotal[j].dayDate, 'dd')) === i) {
                        temp = resTotal[j].totalValue
                        break
                    }
                }
                totalSum += Number(temp)
                this.totalList.push(temp)
            }
            this.totalList.push(totalSum)
            // 插入合计数据
            this.dayArr.push({ day: this.dayArr.length + 1, type: '合计' })
            // this.dayArr.push({ day: 33, type: '店内各项销售占比' })
            // this.dayArr.push({ day: 34, type: '各店销售占比' })
            // 处理数据将每一个店的时间对应上列
            const tableData = []
            // console.log('this.dayArr', this.dayArr)
            res.map((dayData, index) => {
                const oneDay = []
                for (let i = 1; i <= days; i++) {
                    let temp = { day: i }
                    for (let j = 0; j < dayData.length; j++) {
                        if (Number(Tools.fmtLong2DateTime(dayData[j].dayDate, 'dd')) === i) {
                            temp = { ...temp, ...dayData[j] }
                            break
                        }
                    }
                    oneDay.push(temp)
                }
                // 求合
                oneDay.push({
                    dailyIncomeScrapingCard: this.mp[index].dailyIncomeScrapingCardTotal,
                    dailyOutScrapingCard: this.mp[index].dailyOutScrapingCardTotal,
                    nextDailyOutScrapingCard: this.mp[index].nextDailyOutScrapingCardTotal,
                    totalPayables: this.mp[index].totalPayables
                })
                // 处理接口数据
                // oneDay.push({
                //     dailyIncomeScrapingCard: this.mp[index].dailyIncomeScrapingCardProportion.toFixed(2) + '%',
                //     dailyOutScrapingCard: this.mp[index].dailyOutScrapingCardProportion.toFixed(2) + '%',
                //     nextDailyOutScrapingCard: this.mp[index].nextDailyOutScrapingCardProportion.toFixed(2) + '%'
                // })
                // oneDay.push({
                //     totalPayables: this.ep[index].field_percentage.toFixed(2) + '%'
                // })

                tableData.push(oneDay)
            })
            console.log('tableData', tableData)

            this.tableData = tableData
        },
        // 改变样式
        rowStyle(obj) {
            if (obj.row.type) {
                return { backgroundColor: '#F5F7FA !important' }
            }
        },
        //获取窗口高度
        getWinHeight() {
            let that = this
            this.heightL = window.innerHeight - 220
            window.addEventListener('resize', () => {
                that.heightL = window.innerHeight - 270
            })
        },

        // 导出
        exportEcx() {
            this.exportExceldata(new Date().toLocaleDateString() + '导出的列表', 'tabledatalist')
        },

        exportExceldata(filename, tableId) {
            var xlsxParam = { raw: true }; // 导出的内容只做解析，不进行格式转换
            var table = document.querySelector("#" + tableId).cloneNode(true);
            var wb = XLSX.utils.table_to_book(table, xlsxParam);
            /* 获取二进制字符进行输出 */
            var wbout = XLSX.write(wb, {
                bookType: "xlsx",
                bookSST: true,
                type: "array",
            });
            try {
                FileSaver.saveAs(
                    new Blob([wbout], { type: "application/octet-stream" }),
                    filename + ".xlsx"
                );
            } catch (e) {
                if (typeof console !== "undefined") {
                    console.log(e, wbout);
                }
            }
            return wbout;
        },
    }
}
</script>

<style>
.occupy-black {
    background-color: #F5F7FA !important;
    border-bottom: #F5F7FA !important;
}
</style>
